package com.yql.commonextend.utils;


import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

public class EncryptTool {
    private byte[] encryptString(byte[] data, byte[] rawKeyData)
            throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, IllegalStateException {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(rawKeyData);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(1, key, sr);
        return cipher.doFinal(data);
    }

    public String encryptString(String rawStr, String rawKey)
            throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, IllegalStateException, IOException {
        byte[] rawStrData = rawStr.getBytes();
        byte[] rawKeyData = rawKey.getBytes();
        byte[] encryptData = encryptString(rawStrData, rawKeyData);
        String encryptStr = new BASE64Encoder().encode(encryptData);
        byte[] c = encryptStr.getBytes();
        StringBuilder strBuf = new StringBuilder();
        for (int t : c) {
            String str = Integer.toHexString(t);
            if (str.length() == 1)
                strBuf.append(0);
            strBuf.append(Integer.toHexString(t));
        }
        return strBuf.toString();
    }
}

